package cn.schoolwow.quickserver.domain;

import cn.schoolwow.quickserver.response.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 响应元数据
 */
public class HttpResponseMeta {
    /**
     * 协议版本
     */
    public String protocol = "HTTP/1.1";

    /**
     * 状态
     */
    public int status;

    /**
     * 消息
     */
    public String statusMessage;

    /**
     * http头部
     */
    public Map<String, List<String>> headers = new HashMap<>();

    /**
     * 编码格式
     */
    public String charset = "utf-8";

    /**
     * 编码格式
     */
    public String contentType;

    /**
     * 输出流大小
     */
    public long contentLength;

    /**
     * 返回头部内容
     */
    public String headerString;

    /**
     * body输入流
     */
    public InputStream bodyInputStream;

    /**
     * 输出流
     */
    public OutputStream outputStream;

    /**
     * 控制器方法输出结果
     * */
    public String result;

    public Client client;

    private Logger logger = LoggerFactory.getLogger(HttpResponseMeta.class);

    {
        headers.put("Date", Arrays.asList(new Date().toString()));
        headers.put("Server", Arrays.asList("QuickServer2"));
    }

    public HttpResponseMeta(Client client) {
        this.client = client;
    }

    /**
     * 设置返回状态码
     */
    public void httpStatus(HttpStatus httpStatus) {
        this.status = httpStatus.status;
        this.statusMessage = httpStatus.statusMessage;
    }

    /**
     * 填充http头部
     */
    public void fillHeadStream() throws IOException {
        if (client.httpResponseMeta.status == 0) {
            client.httpResponseMeta.httpStatus(HttpStatus.OK);
        }
        if (null != contentType) {
            logger.trace("[设置ContentType]{}",contentType + "; charset=" + charset);
            headers.put("Content-Type", Arrays.asList(contentType + "; charset=" + charset));
        }
        if (contentLength > 0) {
            headers.put("Content-Length", Arrays.asList(contentLength + ""));
        }
        if (null == headerString) {
            StringBuilder builder = new StringBuilder();
            builder.append(protocol + " " + status + " " + statusMessage + "\r\n");
            Set<Map.Entry<String, List<String>>> entrySet = headers.entrySet();
            for (Map.Entry<String, List<String>> entry : entrySet) {
                for (String value : entry.getValue()) {
                    builder.append(entry.getKey() + ": " + value + "\r\n");
                }
            }
            builder.append("\r\n");
            headerString = builder.toString();
            outputStream.write(headerString.getBytes(charset));
            outputStream.flush();
        } else {
            logger.warn("[头部报文已写入]");
        }
    }
}
